package org.example.controller;

import lombok.extern.slf4j.Slf4j;
import org.example.common.BaseResponse;
import org.example.common.ResultUtils;
import org.example.constant.UserConstant;
import org.example.domain.User;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;

@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {
    
    @Value("${file.upload.path}")
    private String fileUploadPath;
    
    @GetMapping("/get")
    public void getFile(HttpServletRequest request, HttpServletResponse response) {
        User user = (User)request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        String fileName = user.getAvatar().substring(0,10)+"\\"+user.getAvatar().substring(10);
        try {
            // 防止文件名中包含非法路径
            fileName = fileName.replace("..", "");
            File file = new File(fileUploadPath + fileName);

            if (!file.exists()) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                return;
            }

            // 根据文件后缀设置响应类型
            String suffix = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
            switch (suffix) {
                case ".png":
                    response.setContentType("image/png");
                    break;
                case ".gif":
                    response.setContentType("image/gif");
                    break;
                default:
                    response.setContentType("image/jpeg");
            }

            // 将文件写入响应
            try (FileInputStream fis = new FileInputStream(file);
                 OutputStream os = response.getOutputStream()) {
                byte[] buffer = new byte[1024];
                int len;
                while ((len = fis.read(buffer)) != -1) {
                    os.write(buffer, 0, len);
                }
                os.flush();
            }
        } catch (IOException e) {
            log.error("文件读取失败", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
}